<template>
  <div class="search-div">
    <!-- 搜索表单 -->
    <el-form label-width="70px" size="small">
      <el-form-item label="角色名称">
        <el-input
          style="width: 100%"
          placeholder="角色名称"
          v-model="queryDto.roleName"
        ></el-input>
      </el-form-item>
      <el-row style="display:flex">
        <el-button type="primary" size="small" @click="searchSysRole">
          搜索
        </el-button>
        <el-button size="small" @click="resetData">重置</el-button>
      </el-row>
    </el-form>

    <!-- 添加按钮 -->
    <div class="tools-div">
      <el-button type="success" size="small" @click="addShow">添 加</el-button>
    </div>

    <!-- 添加角色表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="title" width="30%">
      <el-form label-width="120px">
        <el-form-item label="角色名称">
          <el-input v-model="saveRole.roleName" />
        </el-form-item>
        <el-form-item label="角色Code">
          <el-input v-model="saveRole.roleCode" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分配菜单的对话框 
      // tree组件添加ref属性，后期方便进行tree组件对象的获取(ref获取组件的实例,使用组件的API,便于渲染数据)
    -->
    <el-dialog v-model="dialogMenuVisible" title="分配菜单" width="40%">
      <el-form label-width="80px">
        <!--:data="sysMenuTreeList" 展示数据 -->
        <el-tree
          :data="sysMenuTreeList"
          ref="tree"
          show-checkbox
          default-expand-all
          :check-on-click-node="true"
          node-key="id"
          :props="defaultProps"
        />
        <el-form-item>
          <el-button type="primary" @click="onSaveAssignMenu">提交</el-button>
          <el-button @click="dialogMenuVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--- 角色表格展示数据 -->
    <el-table :data="list" style="width: 100%" stripe="true">
      <el-table-column prop="roleName" label="角色名称" width="180" />
      <el-table-column prop="roleCode" label="角色code" width="180" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" align="center" width="280" #default="scope">
        <el-button type="primary" size="small" @click="updateShow(scope.row)">
          修改
        </el-button>
        <el-button type="danger" size="small" @click="deleteById(scope.row)">
          删除
        </el-button>
        <el-button
          type="warning"
          size="small"
          @click="showAssignMenu(scope.row)"
        >
          分配菜单
        </el-button>
      </el-table-column>
    </el-table>

    <!--分页条-->
    <el-pagination
      v-model:current-page="pageParams.page"
      v-model:page-size="pageParams.limit"
      @size-change="getPageData"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next"
      :total="total"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {
  getPageAPI,
  saveRoleAPI,
  deleteRoleAPI,
  updateRoleAPI,
  getFindByRoleIdAssignMenu,
  postSaveAssignMenu,
} from '@/api/role'
import { ElMessage, ElMessageBox } from 'element-plus'
////////////////////////////////////////////////////////////////////分页查询
// 分页条总记录数
let total = ref(0)

//分页pageNum,pageSize
const pageParamsForm = {
  page: 1, //当前页
  limit: 10, //每页记录数
}

const title = ref('')

// 定义表格数据模型
let list = ref([])

const pageParams = ref(pageParamsForm) // 将pageParamsForm包装成支持响应式的对象

//搜索表单数据模型
const queryDto = ref({
  roleName: '',
})

// 页面加载完毕以后请求后端接口获取数据
onMounted(() => {
  getPageData()
})

//搜索按钮事件
const searchSysRole = () => {
  getPageData()
}
//重置按钮事件
const resetData = () => {
  queryDto.value.roleName = ''
  getPageData()
}

//调佣分页查询后端接口
const getPageData = async () => {
  const { data } = await getPageAPI(
    pageParams.value.page,
    pageParams.value.limit,
    queryDto.value
  )
  list.value = data.list
  total.value = data.total
}

/////////////////////////////////////////////////////////////////////////////////////////添加角色
//定义变量控制添加表单的显示
const dialogVisible = ref(false)
//添加按钮事件,
const addShow = () => {
  title.value = '添加角色'
  saveRole.value.roleCode = ''
  saveRole.value.roleName = ''
  //表单显示
  dialogVisible.value = true
}
//添加和修改表单数据模型
const saveRoleFormModel = {
  id: '',
  roleCode: '',
  roleName: '',
}
//把添加表单数据模型,转换为响应式数据
const saveRole = ref(saveRoleFormModel)

//调佣添加角色后端接口
const submit = async () => {
  if (!saveRole.value.id) {
    const { code } = await saveRoleAPI(saveRole.value)
    if (code === 200) {
      dialogVisible.value = false
      ElMessage.success('添加角色成功！')
      getPageData()
    }
  } else {
    ///////////////////////////////////////////////////////////////////////////////////修改角色
    const { code } = await updateRoleAPI(saveRole.value) ////////////////调佣后端修改角色接口
    if (code === 200) {
      dialogVisible.value = false
      ElMessage.success('修改角色成功！')
      getPageData()
    }
  }
}
const updateShow = row => {
  saveRole.value = { ...row }
  title.value = '修改角色'
  dialogVisible.value = true
}
/////////////////////////////////////////////////////////////////////////////////////////////////////删除角色
//删除按钮事件,调用后端接口
const deleteById = row => {
  ElMessageBox.confirm('是否确定删除?', 'warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const { code } = await deleteRoleAPI(row.id)
    if (code === 200) {
      ElMessage.success('删除成功!')
      pageParams.value.page = 1
      getPageData()
    }
  })
}
//=====================================分配菜单===========================================
const defaultProps = {
  children: 'children',
  label: 'title',
}
//控制弹窗是否显示
const dialogMenuVisible = ref(false)
//定义变量存储展示数据
const sysMenuTreeList = ref([])
// 树对象实例,便于使用组件API
const tree = ref()
// 默认选中的菜单数据集合
let roleId = ref()
//打开弹窗
const showAssignMenu = async row => {
  dialogMenuVisible.value = true
  roleId = row.id
  //调用后端分配菜单接口
  const { data } = await getFindByRoleIdAssignMenu(row.id)
  //封装数据.data.menuList 是后端封装的名称
  sysMenuTreeList.value = data.menuList //所有的树形菜单数据
  tree.value.setCheckedKeys(data.roleMenuIdList) //根据角色id查询出对应的菜单id,数据回显,选中角色对应的菜单
}
//=====================================保存分配的菜单id=============================================
//分配菜单提交按钮事件
const onSaveAssignMenu = async () => {
  //获取选中的菜单节点
  const checkedMenuNodes = tree.value.getCheckedNodes()
  //遍历节点,获取选中的菜单id
  const checkedMenuIdList = checkedMenuNodes.map(node => {
    return {
      id: node.id,
      isHalf: 0,
    }
  })

  // 获取半选中的节点数据，当一个节点的子节点被部分选中时，该节点会呈现出半选中的状态
  const haIfCheckedNodes = tree.value.getHalfCheckedNodes()
  const halfCheckedMenuIdList = haIfCheckedNodes.map(node => {
    return {
      id: node.id,
      isHalf: 1,
    }
  })

  // 将选中的节点id和半选中的节点的id进行合并
  const menuIdList = [...checkedMenuIdList, ...halfCheckedMenuIdList]

  //封装数据,传给后端
  const assignMenuDto = {
    roleId: roleId, //角色id
    menuIdList: menuIdList, //菜单id,和isHaIf是否是全选和半选（0全选,1半选）
  }
  const { code } = await postSaveAssignMenu(assignMenuDto)
  if (code === 200) {
    ElMessage.success('保存分配菜单成功!')
    dialogMenuVisible.value = false
  }
}
</script>

<style scoped>
.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
</style>
